<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="园所名称" prop="title">
          <el-input
            v-model="queryParams.title"
            @input="handleInput"
            placeholder="请输入园所名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['student:studentEnroll:add']"
          >新增</el-button>
        </el-col>
      </el-row>
  
      <el-table v-loading="loading" :data="studentEnrollList" >
        <el-table-column type="index" align="center" label="序号" :index="customeIndex" width="80"></el-table-column>
        <el-table-column label="学期" align="center" prop="schoolName" />
        <el-table-column label="园所名称" align="center" prop="schoolName" />
        <el-table-column label="招生人数" align="center" prop="total" />
        <el-table-column label="报名人数" align="center" prop="signups" />
        <el-table-column label="状态" align="center" prop="status"  >  
          <template slot-scope="scope">
          <el-switch 
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatus(scope.row)"
          ></el-switch>
          
         </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['student:studentEnroll:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['student:studentEnroll:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-info"
              @click="showEnrollmentLink(scope.row)"
            >报名链接</el-button>
          </template>
        </el-table-column>

        <!-- 报名链接弹框 -->
      
      </el-table>
      <el-dialog
        title="报名链接"
        :visible.sync="showEnrollmentLinkDialog"
        width="30%"
        center
      >
        <!-- 显示报名链接 -->
        <p>{{ enrollmentLink }}</p>

        <!-- <router-link :to="{ path: enrollmentLink }">
          {{ enrollmentLink }}
        </router-link> -->

      </el-dialog>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改招生计划对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="园所名称" prop="name">
            <el-select v-model="form.name" clearable filterable placeholder="请选择">
                          <el-option
                            v-for="item in schoolList"
                            :key="item.code"
                            :label="item.title"
                            :value="item.code">
                          </el-option>
                        </el-select>
          </el-form-item>
          <el-form-item label="招生人数" prop="total">
            <el-input v-model="form.total" type='number' placeholder="请输入招生人数" />
          </el-form-item>
          <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
             >{{dict.dictLabel}}</el-radio>
           </el-radio-group>
        </el-form-item>
          <!-- <el-form-item label="报名人数" prop="signups" v-if="form.id">
            <el-input v-model="form.signups" disabled placeholder="请输入报名人数" />
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getToken } from "@/utils/auth";
  import { selectSpecialty} from "@/api/base/specialty";
  import {changeStatus,getstudentEnrollList,addstudentEnroll,updatestudentEnroll,delstudentEnroll} from "@/api/qu/xwgl.js";
  import { schoolList } from "@/api/qu/yssctj";
  export default {
    name: "StudentEnroll",
    data() {
      return {
        showEnrollmentLinkDialog: false, // 控制报名链接弹框的显示与隐藏
        enrollmentLink: this.generateEnrollmentLink(),
        schoolList:[],
        // 遮罩层
        loading: true,
        studentEnrollList:[],
        // 选中数组
        ids: [],
        id:'',
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          status: null
        },
        // 表单参数
        form: {
          name:'',
          total:'',
          status:0

        },
        // 表单校验
        rules: {
          name: [
            { required: true, message: "园所名称不能为空", trigger: "blur" }
          ],
          total: [
            { required: true, message: "招生人数不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getschoolList()
      this.getDicts("common_status").then(response => {
        this.statusOptions = response.data;
      });
      selectSpecialty({'status':1}).then(response => {
        this.specialtyList = response.rows;
      });
    },
    methods: {
      generateEnrollmentLink() {
        const baseUrl = window.location.origin + window.location.pathname + window.location.search;
        // 输出基础 URL
        console.log("111",baseUrl);
        const enrollmentLink = baseUrl + '#' + 'enrollment-link';
        return enrollmentLink;
    },
      showEnrollmentLink(row) {
        this.enrollmentLink = this.generateEnrollmentLink();
        this.enrollmentLink = this.enrollmentLink + '?schoolName=' + row.schoolName;
        console.log("11",this.enrollmentLink)
      // 点击报名链接按钮时显示弹框
      this.showEnrollmentLinkDialog = true;
      console.log(this.showEnrollmentLinkDialog)
    },
      /** 查询招生计划列表 */
      async  getList() {
        this.loading = true;
        try {
          const obj={
            schoolName:this.queryParams.title,
            status:this.queryParams.status,
            pageNum: this.queryParams.pageNum,
            pageSize: this.queryParams.pageSize,
            
          }
          const data =  await getstudentEnrollList(obj);
          this.studentEnrollList = data.rows;
          this.total = data.total;
          this.loading = false;
        } catch (error) {
           console.log(error);
        }
        
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
        //获取学校列表
      async getschoolList(){
        const data = await schoolList();
        this.schoolList=data.rows;

       },
           // 序号
      customeIndex(index){
           return index+1+(this.queryParams.pageNum-1)*this.queryParams.pageSize
        },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          total: null,
          status: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleInput(val){
        let regtszf = /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/g ;// 特殊字符正则
        let regkg = /[ ]/g;// 空格正则
        this.queryParams.title = val.replace(regtszf, '').replace(regkg, '');
         },
      /**启用 或禁用操作 */
    handleStatus (row) {
      const ids = row.id || this.ids;
      let text = row.status === "0" ? "关闭" : "开启";
      this.$confirm('是否确认将选中的招生计划设置为' + text +  '状态吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeStatus({id:ids, status: row.status});
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
   
      /** 新增按钮操作 */
      handleAdd() {
        this.id=''
        this.reset();
        this.open = true;
        this.title = "添加招生方案";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.$nextTick(()=> {
             this.$set(this.form, 'name', row.schoolCode)
           })
           this.id=row.id;
          this.form.total=row.total;
          this.form.status=row.status;
          this.open = true;
          this.title = "修改招生方案";
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate( async valid => {
          if (valid) {
            if (this.id!= '') {
              try {
                const obj ={
                  id:this.id,
                  schoolCode:this.form.name,
                  total:this.form.total,
                  status:this.form.status,
                }
                const data =  await updatestudentEnroll(obj)
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } catch (error) {
                console.log(error);
              }
            } else {
              try {
                const obj ={
                  schoolCode:this.form.name,
                  total:parseInt(this.form.total),
                  status:this.form.status,
                }
                const data =  await addstudentEnroll(obj);
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } catch (error) {
                  console.log(error);
              }
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除选中的招生计划?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return delstudentEnroll(ids);
          }).then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
      },
    }
  };
  </script>

<style  lang="scss" scoped>
::v-deep  input::-webkit-inner-spin-button {
 -webkit-appearance: none !important;
}
::v-deep  input[type='number'] {
 -moz-appearance: textfield !important;
}

</style>
  